package com.plugins.http;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpHost;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import com.alibaba.fastjson.JSONObject;
import com.iclient.dao.DaoUtils;
import com.iclient.dao.service.ImgService;


public class LoginTool {
	
	public static void login(){
		try{
			HttpGet httpGet = new HttpGet("http://login.weibo.cn/login/");
			httpGet.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 5.1; rv:33.0) Gecko/20100101 Firefox/33.0");
			httpGet.addHeader("Host", "login.weibo.cn");
			httpGet.addHeader("Origin", "https://login.weibo.cn");
			httpGet.addHeader("Referer", "https://login.weibo.cn/login/");
			CloseableHttpClient httpClient = HttpClients.createDefault();
			CloseableHttpResponse response = httpClient.execute(httpGet, HttpClientContext.create());
			String login_page = EntityUtils.toString(response.getEntity());
			Document document = Jsoup.parse(login_page);
			String action = document.getElementsByTag("form").get(0).attr("action");
			Element e = document.getElementsByAttributeValue("alt", "请打开图片显示").get(0);
			Map<String, String> param = filterLoginData(document);
			HttpGet httpGet0 = new HttpGet(e.attr("src"));
			CloseableHttpResponse response0 =  httpClient.execute(httpGet0);
			ImgService imgService = (ImgService) DaoUtils.getBean("imgService");
			FileUtils.readImg(imgService, response0.getEntity().getContent());
			String code = imgService.getCode();
			if(StringUtils.isNotBlank(code)){
				param.put("code", code);
			}
			HttpPost httpPost = new HttpPost("http://login.weibo.cn/login/" + action);
			List<NameValuePair> pairs = new ArrayList<>();
			for(String key : param.keySet()){
				pairs.add(new BasicNameValuePair(key, param.get(key)));
			}
			httpPost.setEntity(new UrlEncodedFormEntity(pairs));
			CloseableHttpResponse response1 = httpClient.execute(httpPost);
			if(response1.getStatusLine().getStatusCode() == 302){
				String locationUrl = response1.getLastHeader("Location").getValue();
				HttpGet httpget = new HttpGet(locationUrl);
				RequestConfig config = RequestConfig.custom()
						.setProxy(new HttpHost("127.0.0.1", 8888))
						.setCookieSpec(CookieSpecs.STANDARD)
						.setRedirectsEnabled(false)
						.build();
				httpget.setConfig(config);
				httpClient.execute(httpget);
				HttpGet get = new HttpGet("http://weibo.cn");
				get.setConfig(config);
				HttpClientContext context = HttpClientContext.create();
				httpClient.execute(get, context);
				List<Cookie> cookies = context.getCookieStore().getCookies();
				imgService.saveLoginCookie(JSONObject.toJSONString(cookies), "msinalogin");
			}
			httpClient.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	private static Map<String, String> filterLoginData(Document document){
		String passwordfield = document.getElementsByAttributeValue("type", "password").get(0).attr("name");
		String vk = document.getElementsByAttributeValue("name", "vk").get(0).attr("value");
		String capId = document.getElementsByAttributeValue("name", "capId").get(0).attr("value");
		Map<String, String> param = new HashMap<>();
		param.put(passwordfield, "yanghui");
		param.put("mobile", "1002318371@163.com");
		param.put("remember", "on");
		param.put("backURL", "http%3A%2F%2Fweibo.cn");
		param.put("backTitle", "手机新浪网");
		param.put("tryCount", "");
		param.put("vk", vk);
		param.put("capId", capId);
		param.put("submit", "登录");
		param.put("code", "");
		return param;
	}
	
	public static void main(String[] args) {
		//LoginTool.login();
		//String s = "[{"creationDate":1473651670280,"domain":"newlogin.sina.cn","name":"SUB","path":"/crossDomain","persistent":false,"secure":false,"value":"_2A2560lOGDeTxGedI7VYX9ynPyjyIHXVWPX3OrDV9PUJbktAKLUr1kW18hYlAvI36fFIB2DCixJws7kZz6g..","version":0},{"domain":"weibo.cn","expiryDate":1476243670000,"name":"SUB","path":"/","persistent":true,"secure":false,"value":"_2A2560lOGDeTxGedI7VYX9ynPyjyIHXVXxuBOrDV6PUJbkdANLVL2kWo9oh7Kehk0Az8fcx3w6JqnulGEdg..","version":0},{"creationDate":1473651670280,"domain":"sina.cn","name":"SUBP","path":"/","persistent":false,"secure":false,"value":"0033WrSXqPxfM725Ws9jqgMF55529P9D9WFBF2oscyxG5U-JTQVbrCIZ5JpX5oz75NHD95QpSoqXSoMNe027Ws4DqcjGwrDDqgyfIBtt","version":0},{"creationDate":1473651670279,"domain":"sina.cn","name":"_T_WM","path":"/","persistent":false,"secure":false,"value":"5fd17c88046392a27ef1508a0e5b818b","version":0},{"domain":"weibo.cn","expiryDate":1476243654000,"name":"_T_WM","path":"/","persistent":true,"secure":false,"value":"fd9cda4eb8f05e26a335946808cd4a8a","version":0},{"creationDate":1473651670280,"domain":"sina.cn","name":"gsid_CTandWM","path":"/","persistent":false,"secure":false,"value":"4uy5bad51UIpOOaaLNWPz6Z3D50","version":0},{"domain":"weibo.cn","expiryDate":1476243670000,"name":"gsid_CTandWM","path":"/","persistent":true,"secure":false,"value":"4uy5bad51UIpOOaaLNWPz6Z3D50","version":0}]"
	}
}
